#include <iostream>
using std::cout;
using std::cin;
using std::endl;
//在类之外定义一个全局类AutoRelease，
//实现单例模式的自动释放

//单例Singleton
class Singleton {
public:
    static Singleton* getInstance() {
        if (ms_instance == nullptr) {
            ms_instance = new Singleton{};
        }
        return ms_instance;
    }
    // static void destroyInstance() {
    //     if (ms_instance) {
    //         delete ms_instance;
    //         ms_instance = nullptr;
    //     }
    // }
    friend class AutoRelease;
private:
    Singleton& operator=(const Singleton&) = delete;
    Singleton(const Singleton&) = delete;
    Singleton(int val = 1)
        :m_val(val)
    {
        cout << "Singleton()" << endl;
    }
    ~Singleton() {
        cout << " ~Singleton()" << endl;
        // if (ms_instance) {
        //     delete ms_instance;
        //     ms_instance = nullptr;
        // }
    }
private:
    static Singleton* ms_instance;
    int m_val;
};//end of class Singleton
//静态成员的初始化
Singleton* Singleton::ms_instance = nullptr;
//AutoRelease类
class AutoRelease {
public:
    AutoRelease(Singleton* p_singleton)
        :m_singleton(p_singleton)
    {
        cout << "AutoRelease(Singleton * p_singleton)" << endl;
    }
    ~AutoRelease() {
        if (m_singleton) {
            delete m_singleton;
            m_singleton = nullptr;
            cout << "AutoRelease over" << endl;
        }
    }
private:
    Singleton* m_singleton;

};//end of class AutoRelease


void test() {
    AutoRelease autorelease1(Singleton::getInstance());
    cout << Singleton::getInstance() << endl;
    cout << Singleton::getInstance() << endl;
    cout << Singleton::getInstance() << endl;
}
int main() {
    cout << "begin" << endl;
    test();
    cout << "after" << endl;
    return 0;
}